package com.zjuee.gateway.filter;

import com.zjuee.base.bean.response.CommonResultCode;
import com.zjuee.base.bean.response.R;
import com.zjuee.base.model.AuthUser;
import com.zjuee.gateway.utils.HttpResponseUtils;
import com.zjuee.gateway.utils.SecurityUtil;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * 自定义角色校验filter，解决验证失败自动跳转的问题
 *
 * @author wu liang
 * @since 2020/8/13 9:54
 */
public class MyRolesAuthorizationFilter extends AuthorizationFilter {

    /**
     * 角色校验的方法
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object mappedValue) throws Exception {
        AuthUser onlineUser = SecurityUtil.getOnlineUser();
        if (onlineUser == null)
            return false;

        Subject subject = getSubject(servletRequest, servletResponse);
        String[] rolesArray = (String[]) mappedValue;

        //超级管理员，直接放行
//        if (UserType.superadmin.toString().equals(onlineUser.getUserType())) {
//            return true;
//        }

        // 资源没有角色要求
        if (rolesArray == null || rolesArray.length == 0) {
            return true;
        }

        // 用户含有一个角色
        for (int i = 0; i < rolesArray.length; i++) {
            if (subject.hasRole(rolesArray[i])) {
                return true;
            }
        }

        return false;
    }

    // 校验失败时，直接返回错误Json
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = getSubject(request, response);
        if (subject.getPrincipal() == null) {
            // saveRequestAndRedirectToLogin(request, response);

            // 只去校验登录，不进行重定向
            saveRequest(request);
            HttpResponseUtils.sendJsonMessage(response, R.fail(CommonResultCode.UN_AUTH));
        } else {
            String unauthorizedUrl = getUnauthorizedUrl();
            if (StringUtils.hasText(unauthorizedUrl)) {
                WebUtils.issueRedirect(request, response, unauthorizedUrl);
            } else {
                // WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
                // 直接返回錯誤信息
                // 为options试探请求给出响应
                if(WebUtils.toHttp(request).getMethod().equals(RequestMethod.OPTIONS.name())) {
                    WebUtils.toHttp(response).setStatus(HttpStatus.OK.value());
                    return true;
                }
                HttpResponseUtils.sendJsonMessage(response, R.fail(CommonResultCode.UN_HAS_ROLES));
            }
        }
        return false;
    }
}
